import axios from 'axios'
import { ElMessage } from 'element-plus'  // 引入el 提示框，这个项目里用什么组件库这里引什么
import router from "@/router";
export function request(config) {
  // 创建axios的实例
  const instance = axios.create({
    baseURL: 'https://xyx.xintujing.online:8000/api',
    // baseURL: 'http://10.119.116.128:8000/api',
    timeout: 100000
  })
    let token = JSON.parse(localStorage.getItem('yxUserInfo'))?.token || ''
    // 请求拦截器配置
    instance.interceptors.request.use(config => {
      console.log(14,config);
      config.headers = {
        'Content-Type':'application/json;charset=UTF-8',        // 传参方式json
      };
      if (config.url!='/login') {
        config.headers.Authorization = 'Bearer ' + token
      }
      return config
    }, error => {
      console.log(error)
      return Promise.error(error)
    }
  )
  // 响应拦截器配置
  instance.interceptors.response.use(response => {
    console.log(response)
    if (response.data.code == -401) {
      ElMessage.warning("无权访问")
      router.push('/login')
    }else{
      return response.data
    }
  }, error => {
    console.log(error);
    switch (error.response.code) {
      case "-401":
        ElMessage.warning("无权访问")
        router.push('/login')
        break
      default:
        return Promise.reject(error)
    }
    return Promise.reject(error)
  })
  // 发送真正的网络请求
  return instance(config);
}
export default request